<?php
$related = new Product;
$related->unsetAttributes();
if (isset($_GET['Product']))
{
    $related->attributes = $_GET['Product'];
    if (isset($_GET['Product']['id']))
        $related->id = $_GET['Product']['id'];
    if (isset($_GET['Product']['category']))
        $related->category = $_GET['Product']['category'];
}
$isRelated = (boolean) isset($_GET['related']) ? $_GET['related'] : true;
$merge = new CDbCriteria;
if ($isRelated)
{
    $merge->distinct = false;
    $merge->join = 'INNER JOIN '.SITE_ID.'_shop_cross_sale prp ON prp.cross_sale_id = t.id';
    $merge->compare('prp.product_id', $model->id);
    $merge->order = 'prp.ordering';
}
else
{
    $merge->addCondition('t.id NOT IN (SELECT cross_sale_id FROM '.SITE_ID.'_shop_cross_sale WHERE product_id = '.Yii::app()->db->quoteValue($model->id).')');
    $merge->compare('t.id', '<>'.$model->id);
    $merge->compare('t.status', true);
}
/** @var $model Product */
$this->widget('Xpress.extensions.web.widgets.XGridView', array(
    'id' => 'relative-grid',
    'dataProvider' => $related->search($merge),
    'filter' => $related,
    'selectableRows' => 2,
    'htmlOptions' => array('class' => 'table table-hover'),
    'afterAjaxUpdate' => 'js:$.afterAjaxUpdate',
    'columns' => array(
        array(
            'class' => 'CCheckBoxColumn',
            'value' => '$data->id',
            'htmlOptions' => array('width' => '3%'),
        ),
        array(
            'name' => 'gallery',
            'type' => 'raw',
            'filter' => false,
            'value' => 'CHtml::image($data->getProductItems(true), $data->name)',
        ),
        array(
            'name' => 'name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->name,Yii::app()->controller->createUrl("update",array("id"=>$data->id)),array("class"=>"xtarget-detail"))'
        ),
        array(
            'name' => null,
            'header' => 'Sub Product',
            'filter' => CHtml::activeTextField($related,'id[sku]',array('placeholder'=>'SKU')),
            'value' => function ($data) {
                $subProducts = $data->subProduct;
                if (is_array($subProducts) && count($subProducts)) {
                    foreach ($subProducts as $model) {
                        echo '<p id="sub_product_'.$model->id.'">';
                        echo CHtml::link($model->sku, array('/Shop/admin/subProduct/update', 'id' => $model->id, 'product_id' => $data->id), array('class' => 'xtarget-detail'));
                        echo ' ';
                        echo CHtml::ajaxLink('[x]', array('/Shop/admin/subProduct/delete', 'id' => $model->id), array(
                            'type' => 'POST',
                            'dataType' => 'json',
                            'success' => 'js:function(res){
                                if (res["error"] == undefined)
                                {
                                    $("#sub_product_'.$model->id.'").remove();
                                }
                                else
                                    alert(res["msg"]);
                            }'
                        ), array('confirm' => 'Are you sure?'));
                        echo '</p>';
                    }
                }
            }
        ),
        array(
            'name'=>'product.categories',
            'type'=>'raw',
            'filter' => CHtml::activeDropDownList($related, 'category', Yii::app()->controller->getCategoriesForUpdate(), array('prompt' => '---')),
            'value'=>function($data){
                return implode(",",array_keys($data->categories(array("index"=>"title"))));
            }
        ),
        array(
            'header' => 'Related',
            'filter' => CHtml::dropDownList('related', $isRelated, array(1 => 'Yes', 0 => 'No')),
            'type' => 'raw',
            'htmlOptions' => array('style' => 'text-align:center'),
            'value' => $isRelated ? 'CHtml::link("<i class=\'icon icon-remove\'></i>", "#".$data->id, array("title"=>"Remove related","class"=>"toggle-status"))' : 'CHtml::link("<i class=\'icon icon-plus\'></i>", "#".$data->id, array("title"=>"Add related","class"=>"toggle-status"))',
        ),
    ),
));

$ajaxUrl = $this->createUrl("/Xpress/service/ajax");
Yii::app()->clientScript->registerScript('toggle-status', '
$(".toggle-status").live("click",function(e){
    if (!confirm("Are you sure you want to "+($("#related").val() == 0 ? "add" : "remove")+" this product")) return false;
        var c=$(this), relativeProductId = $(this).attr("href").replace("#", "");
            $.ajax({
                type:"POST",
                url:"' . $ajaxUrl . '",
                data: {
                    SID : "Shop.Product.relative",
                    productId : '.$model->id.',
                    relativeProductId : relativeProductId
                },
                success:function(){
                    $.fn.yiiGridView.update("relative-grid");
                }
            })
            return false;
        });
', CClientScript::POS_READY);


$productId = CPropertyValue::ensureInteger($model->id);
$js = <<<EOP
$.afterAjaxUpdate = function(){
    if ($('.filters #related option:selected').val() == 1)
    {
        $('#relative-grid tbody tr').each(function(){
            $('td:eq(1)',this).addClass('handle');
            var id = $('td:eq(0) input',this).val();
            $(this).attr('id',id);
        });
        $( "#relative-grid tbody" ).sortable({
            handle : '.handle',
            update : function( event, ui ){
                var ids = $( "#relative-grid tbody" ).sortable('toArray');
                $.post('$ajaxUrl', {
                    SID : 'Shop.Product.updateOrdering',
                    ids : ids,
                    productId : $productId,
                },function(){});
            }
        });
        $( "#relative-grid tbody" ).disableSelection();
    }
}
$.afterAjaxUpdate();
EOP;
cs()->registerScript(__CLASS__.'Sort', $js, CClientScript::POS_END);